package com.heima.behavior.service.impl;

import com.heima.behavior.service.IApBehaviorEntryService;
import com.heima.behavior.service.IApReadBehaviorService;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.threadlocal.AppThreadLocalUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.mongodb.core.query.UpdateDefinition;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
@Slf4j
public class ApReadBehaviorService implements IApReadBehaviorService {

    @Autowired
    private IApBehaviorEntryService apBehaviorEntryService;
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * APP 端-文章详情页-记录用户的阅读行为
     * @param readBehaviorDTO
     * @return
     */
    @Override
    public ResponseResult handleRead(ReadBehaviorDTO readBehaviorDTO) {
        //1.校验参数
           //1.1校验登录状态(阅读行为，不管是否登录都会被记录)
        Integer userId = AppThreadLocalUtils.getUser();
        if(userId == null || userId.intValue() == 0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN, "查看文章详情需要先登录");
        }
            //1.2查询用户行为实体
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(userId, null);
        if(apBehaviorEntry == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "获取用户行为实体失败");
        }
            //1.3检查阅读行为是否存在
        Query query = Query.query(Criteria.where("entry_id").is(apBehaviorEntry.getId()).and("article_id").is(readBehaviorDTO.getArticleId()));
        ApReadBehavior apReadBehavior = mongoTemplate.findOne(query, ApReadBehavior.class);
        //2.保存用户的阅读行为
        if(apReadBehavior == null){
            //2.1不存在，新增用户阅读行为
            apReadBehavior = new ApReadBehavior();
            apReadBehavior.setEntryId(apBehaviorEntry.getId());
            apReadBehavior.setArticleId(readBehaviorDTO.getArticleId());
            apReadBehavior.setCount((short) 1);
            apReadBehavior.setReadDuration(readBehaviorDTO.getReadDuration());
            apReadBehavior.setPercentage(readBehaviorDTO.getPercentage());
            apReadBehavior.setLoadDuration(readBehaviorDTO.getLoadDuration());
            apReadBehavior.setCreatedTime(new Date());
            apReadBehavior.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehavior);
        }else{
            //2.2存在，修改用户阅读行为的阅读数
            Update update = new Update().set("count", apReadBehavior.getCount() + 1).set("updated_time", new Date());
            mongoTemplate.findAndModify(query,update,ApReadBehavior.class);
        }
        //3.返回响应
        return ResponseResult.okResult();
    }
}
